/*
题目链接:https://leetcode.cn/problems/minimum-domino-rotations-for-equal-row/description/?envType=daily-question&envId=2025-05-03
*/

//题解代码:

class Solution {
public:
    int minDominoRotations(vector<int>& tops, vector<int>& bottoms) {
        int n = tops.size();
        int p1 = tops[0],p2 = bottoms[0];
        for(int i=1;i<n;++i){
            if(p1 != tops[i] && p1 != bottoms[i]){
                p1 = -1;
            }
            if(p2 != tops[i] && p2 != bottoms[i]){
                p2 = -1;
            }
        }
        auto f = [&](vector<int>& v,int x){
            int ret = 0;
            for(auto& it : v) ret += it==x;
            return ret;
        };
        int ans = INT_MAX;
        if(p1 != -1){
            int ret1 = f(tops,p1);
            int ret2 = f(bottoms,p1);
            ans = min(ans,min(n-ret1,n-ret2));
        }
        if(p2 != -1){
            int ret1 = f(tops,p2);
            int ret2 = f(bottoms,p2);
            ans = min(ans,min(n-ret1,n-ret2));
        }
        return ans == INT_MAX ? -1 : ans;
    }
};
